import React, { useState } from 'react';
import { Button, Input, message } from 'antd';
import Modals from '@/components/modals/Modals';
import dayjs from 'dayjs';
import { DatasetsContext } from '../../context';
import { useContextSelector } from 'use-context-selector';
import knowService from '@/api/services/knowService';

const PRESETS = [
  { label: '一周', value: 7 },
  { label: '一个月', value: 30 },
  { label: '一年', value: 365 },
  { label: '自定义', value: 'custom' },
];

interface OvertimeModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: () => void;
}

const OvertimeModal: React.FC<OvertimeModalProps> = ({ open, onCancel, onOk }) => {
  const [selected, setSelected] = useState<number | string | null>(null);
  const [customDays, setCustomDays] = useState<string>('');
  const { selectedTreeKeys, fullTreeData, setSelectedTreeKeys } = useContextSelector(
    DatasetsContext,
    (s) => s,
  );

  // 选中预设
  const handlePresetClick = (val: number | string) => {
    setSelected(val);
    if (val !== 'custom') setCustomDays('');
  };

  // 确定
  const handleOk = async () => {
    let days = 0;
    if (selected === 'custom') {
      days = Number(customDays);
      if (!days || days <= 0) {
        message.warning('请输入有效天数');
        return;
      }
    } else if (typeof selected === 'number') {
      days = selected;
    } else {
      message.warning('请选择延长时间');
      return;
    }
    const selectedIds: string[] = fullTreeData
      .filter((item) => selectedTreeKeys.includes(item._id as string))
      .map((item) => item.collectionId as string);
    const selectedData = fullTreeData.filter((item) =>
      selectedIds.includes(item.collectionId as string),
    );
    try {
      const collectionIdList = selectedData.map((item) => {
        const base = item.experiodTimes ? dayjs(item.experiodTimes) : dayjs();
        const next = base.add(days, 'day').format('YYYY-MM-DD HH:mm:ss');
        return {
          collection_id: item.collectionId as string,
          expired_time: next,
        };
      });
      await knowService.postUpdateExpired({
        collectionIdList,
      });
      setSelectedTreeKeys([]);
      message.success('延长成功');
    } catch (error) {
      message.error('延长失败');
    }
    onOk();
    handleCancel();
  };
  // 关闭时重置
  const handleCancel = () => {
    onCancel();
    setSelected(null);
    setCustomDays('');
  };

  return (
    <Modals
      open={open}
      onCancel={handleCancel}
      title="延长时间"
      okText="确定"
      cancelText="取消"
      width={500}
      footer={
        <div className="flex justify-end gap-2 border-t border-t-line-2 p-3">
          <div
            className={`ml-4 flex h-[32px] w-[68px] cursor-pointer items-center justify-center rounded-md border 
                 !border-@brand-color !text-@brand-color
            `}
            onClick={onCancel}
          >
            取消
          </div>
          <div
            style={
              selected ? { background: 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)' } : {}
            }
            className={`ml-4 flex h-[32px] w-[68px]  items-center justify-center rounded-md border text-white 
                 ${
                   selected
                     ? 'cursor-pointer !border-@brand-color '
                     : '!border-@brand-disabled cursor-not-allowed !bg-@brand-color-disabled'
                 }
            `}
            onClick={handleOk}
          >
            完成
          </div>
        </div>
      }
    >
      <div className="flex flex-col gap-4 p-2 pb-0">
        <div className="grid grid-cols-4 gap-3">
          {PRESETS.map((item) => {
            const isActive = selected === item.value;
            if (item.value === 'custom') {
              return (
                <div key={item.label} className="flex">
                  {selected === 'custom' ? (
                    <div
                      className={`flex w-full items-center justify-between rounded-md border pr-3 ${
                        isActive ? '!border-@brand-color' : 'border-line-2'
                      }`}
                    >
                      <Input
                        type="text"
                        inputMode="numeric"
                        pattern="[0-9]*"
                        value={customDays}
                        onChange={(e) => setCustomDays(e.target.value.replace(/[^\d]/g, ''))}
                        className="bg-transparent h-8 !w-20 !border-0 p-0 text-center outline-none focus:shadow-none"
                        placeholder="0"
                      />
                      <span className=" inline-flex h-7 items-center rounded-md   text-sm text-text-4">
                        天
                      </span>
                    </div>
                  ) : (
                    <Button
                      className={`h-10 rounded-full text-base ${
                        isActive ? '!border-@brand-color' : 'border-line-2'
                      }`}
                      onClick={() => handlePresetClick('custom')}
                      block
                    >
                      自定义
                    </Button>
                  )}
                </div>
              );
            }
            return (
              <Button
                key={item.label}
                className={`h-10 rounded-md text-base ${
                  isActive ? 'ring-@brand-color/30 !border-@brand-color ring-1' : 'border-line-2'
                }`}
                onClick={() => handlePresetClick(item.value)}
                block
              >
                {item.label}
              </Button>
            );
          })}
        </div>
      </div>
    </Modals>
  );
};

export default OvertimeModal;
